package top.wangjiu.java.jvm.attribute;

import top.wangjiu.java.jvm.AttributeInfo;
import top.wangjiu.java.jvm.constantinfo.ConstantPoolInfo;

/**
 * 列举出方法中可能抛出的受查异常（即方法描述时throws关键字后列出的异常），与Code属性平级，与Code属性包含的异常表不同
 *
 * number_of_exceptions表示可能抛出number_of_exceptions种受查异常
 *
 * exception_index_table为异常索引集合，一组u2类型exception_index的集合，每一个exception_index为一个指向常量池中一CONSTANT_Class_info型常量的索引，代表该受查异常的类型
 */
public class ExceptionsAttr extends AttributeInfo {

    public final static String NAME = "Exceptions";

    private final short attributeNameIndex;   //属性名索引
    private final int attributeLength;
    //字段值在常量池中的索引，常量池在该索引处的项给出该属性表示的常量值。（例如，值是long型的，在常量池中便是CONSTANT_Long）
    private final short numberOfExceptions;
    private final short[] exceptionIndexTable;

    public ExceptionsAttr(short attributeNameIndex, int attributeLength, short[] exceptionIndexTable){
        this.attributeNameIndex = attributeNameIndex;
        this.attributeLength = attributeLength;
        this.numberOfExceptions = (short) exceptionIndexTable.length;
        this.exceptionIndexTable = exceptionIndexTable;
    }

    @Override
    public short attributeNameIndex() {
        return attributeNameIndex;
    }

    @Override
    public int attributeLength() {
        return attributeLength;
    }

    @Override
    public String toString(ConstantPoolInfo[] poolInfos) {
        StringBuilder sb = new StringBuilder("Exceptions:");
        for (int i = 0; i <numberOfExceptions; i++) {
            sb.append(" "+poolInfos[exceptionIndexTable[i]].toString(poolInfos));
        }
        return sb.toString();
    }
}
